package cluster

import (
	"context"
	"fmt"
	"krm_pro/config"
	"krm_pro/utils"
	"net/http"

	"github.com/gin-gonic/gin"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

// 使用kubernetes secret资源保存多集群kubeconfig 文件，并进行管理
type clusterInfo struct {
	Id          string `json:"id"`
	Displayname string `json:"displayname"`
	City        string `json:"city"`
	District    string `json:"district"`
}

type ClusterConfig struct {
	clusterInfo
	kubeconfig string `json:"kubeconfig"`
}

func (c *ClusterConfig) getClusterStatus() (status string, err error) {
	restconfig, err := clientcmd.RESTConfigFromKubeConfig([]byte(c.kubeconfig))
	if err != nil {
		msg := "Failed to parse kubeconfig file" + err.Error()
		fmt.Println(msg)
		panic(err.Error())
	}

	//创建客户端工具
	clientset, err := kubernetes.NewForConfig(restconfig)
	if err != nil {
		msg := "Failed to create clientset" + err.Error()
		fmt.Println(msg)
		panic(err.Error())
	}

	//获取集群版本
	serverversion, err := clientset.Discovery().ServerVersion()
	if err != nil {
		panic(err.Error())
	}

	clientset.Discovery().RESTClient()
	clusterVersion := serverversion.String()
	fmt.Println("version", clusterVersion)
	status = "ok"
	// ClientSet = clientset
	return status, err
}

func Add(r *gin.Context) {
	clusterConfig := ClusterConfig{}
	if err := r.ShouldBindJSON(&clusterConfig); err != nil {
		r.JSON(http.StatusOK, gin.H{
			"status":  400,
			"message": "集群配置信息错误",
		})
		return
	}

	status, err := clusterConfig.getClusterStatus()
	if err != nil {
		r.JSON(http.StatusOK, gin.H{
			"message": "status is not ok ",
		})
		return
	} else if status == "ok" {
		var clusterCfgSecret corev1.Secret
		clusterCfgSecret.Name = clusterConfig.Id
		clusterCfgSecret.Labels = make(map[string]string)
		clusterCfgSecret.Labels["kubexx.com/cluster.metadata"] = "true"
		clusterCfgSecret.Annotations = make(map[string]string)
		mapType := utils.StructToMap(clusterConfig)
		clusterCfgSecret.Annotations = mapType
		// clusterCfgSecret.Annotations["displayname"] = clusterConfig.Displayname
		// clusterCfgSecret.Annotations["city"] = clusterConfig.City
		// clusterCfgSecret.Annotations["district"] = clusterConfig.District
		clusterCfgSecret.StringData = map[string]string{}
		clusterCfgSecret.StringData["kubeconfig"] = clusterConfig.kubeconfig

		_, err := config.ClientSet.CoreV1().Secrets("").Create(context.TODO(), &clusterCfgSecret, metav1.CreateOptions{})
		if err != nil {
			r.JSON(http.StatusOK, gin.H{
				"status":  400,
				"message": "将集群信息保存至secret资源失败",
			})
			return
		}
		r.JSON(http.StatusOK, gin.H{
			"status":  400,
			"message": "将集群信息保存至secret资源成功",
		})
	}

}
